using System;
using System.IO;
using System.Linq;
using Live2D.Cubism.Editor.Importers;
using Live2D.Cubism.Framework.MotionFade;
using Live2D.Cubism.Rendering;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class GenArtPrefabLive2D : GenArtPrefabBase
    {
        public override ArtModeGenType genPrefabType => ArtModeGenType.Live2D;
        protected override string outputBasePath => "Res/03_Prefabs/Live2D";
        protected override int prefabLayer => (int)LayerConsts.Default;
        protected override string entityGenConfigPath => $"Assets/EditorConfig/ArtToolConfig/EntityGen/Live2D/{entityName}.asset";

        public override void GenArtPrefab(bool withAnimator, bool forceReplaceOld)
        {
            var rPath = this.basePath;
            var rFiles = Directory.GetFiles(rPath, "*", SearchOption.AllDirectories);
            var assetList = CubismCreatedAssetList.GetInstance();
            // Handle any imported Cubism assets.
            for (int i = 0; i < rFiles.Length; i++)
            {
                var assetPath = rFiles[i];
                var importer = CubismImporter.GetImporterAtPath(assetPath);

                if (importer == null)
                {
                    continue;
                }

                try
                {
                    importer.Import();
                }
                catch (Exception e)
                {
                    Debug.LogError("CubismAssetProcessor : Following error occurred while importing " + assetPath);
                    Debug.LogError(e);
                }
            }

            assetList.OnPostImport();

            // 获取animation放进animator并设置animator
            var rPrefab = AssetDatabase.LoadAssetAtPath<GameObject>($"Assets/{this.outputBasePath}/{ArtPrefabToolConstant.Prefab_Sign_Live2D}{this.entityName}.prefab");
            if (withAnimator)
            {
                // 生成动画状态机
                var animatorPath = AnimatorEditorMenu.GenAnimatorByType(basePath, genPrefabType);
                var rAnimatorController = AssetDatabase.LoadAssetAtPath<AnimatorController>(animatorPath);
                if (rAnimatorController != null)
                {
                    for (int i = 0; i < rAnimatorController.layers.Length; i++)
                    {
                        var stateMachine = rAnimatorController.layers[i].stateMachine;

                        if (!stateMachine.behaviours.Any((x) => x is CubismFadeStateObserver))
                        {
                            stateMachine.AddStateMachineBehaviour<CubismFadeStateObserver>();
                            EditorUtility.SetDirty(rAnimatorController);
                        }
                    }
                    
                    var rAniamtor = rPrefab.GetComponent<Animator>();
                    rAniamtor.runtimeAnimatorController = rAnimatorController;
                }
            }
            var fadeController = rPrefab.GetComponent<CubismFadeController>();
            if (fadeController != null)
            {
                var fadeMotionListPath = this.basePath + "/" + this.entityName + ".fadeMotionList.asset";
                var fadeMotions = CubismFadeMotionImporter.GetFadeMotionList(fadeMotionListPath);
                if (fadeMotions == null)
                {
                    return;
                }
                fadeController.CubismFadeMotionList = fadeMotions;
            }
            rPrefab.GetComponent<CubismRenderController>().SortingMode = CubismSortingMode.BackToFrontZ;
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        public override string GetArtModeResPath()
        {
            return String.Empty;
        }

        protected override string defaultGenConfigPath => "Assets/EditorConfig/ArtToolConfig/EntityGen/Common/Entity_Live2D.asset";
    }
}